package com.kkb.shopcenter.handler;

import com.kkb.shopcenter.common.common.HttpResult;
import com.kkb.shopcenter.common.common.ResultEnum;
import com.kkb.shopcenter.common.exception.DefinitionException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

//@ControllerAdvice+@ResponseBody，开启全局的异常捕获，返回JSON
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理自定义异常
     * @return Result
     * @ExceptionHandler 说明捕获哪些异常，对那些异常进行处理。
     */
    @ExceptionHandler(value = DefinitionException.class)
    public HttpResult<Object> customExceptionHandler(DefinitionException e) {
        return HttpResult.defineError(e);
    }

    /**
     * 处理其他异常
     * @return Result
     */
    @ExceptionHandler(value = Exception.class)
    public HttpResult<Object> exceptionHandler(Exception e) {

        if (e instanceof NullPointerException){
            //捕获空指针异常
            return HttpResult.otherError(ResultEnum.NOT_PARAM);
        }else if (e instanceof IllegalAccessException){
            //非法访问异常
            return HttpResult.otherError(ResultEnum.NO_PERMISSION);
        } else{
            return HttpResult.otherError(ResultEnum.SERVER_ERROR);
        }

//        return HttpResult.otherError(ResultEnum.SERVER_ERROR);
    }
}
